import { ChatRoom, User } from "../models/index.js";
import { success, successResponse, errorResponse } from "../utils/result.js";
import lodash from "lodash";
// 搜索朋友/群聊
export const searchUserOrRoom = async (req, res, next) => {
  const { keyword } = req.query;
  try {
    const rooms = await ChatRoom.find({
      name: { $regex: keyword, $options: "i" },
    })
      .populate("creator", "username avatar")
      .populate("members", "username avatar");
    const roomsResult = rooms.map((room) => {
      return lodash.pick(room, [
        "_id",
        "name",
        "description",
        "creator",
        "members",
      ]);
    });
    const user = await User.find({
      username: { $regex: keyword, $options: "i" },
    });
    const userResult = user.map((user) => {
      return lodash.pick(user, ["_id", "username", "avatar"]);
    });

    const searchResult = [...roomsResult, ...userResult];
    res.status(200).json(successResponse(searchResult));
  } catch (error) {
    next(error);
  }
};
